import type { ValuesType, AssetLampPostStateType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { shareEnum } from '~/store/base/typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElFormItem,
  ElSelect,
  ElOption,
  ElSpace,
  ElLink,
  ElButton,
  ElIcon,
  ElInput,
  ElMessage,
  ElMessageBox
} from 'element-plus'
import { Plus, Delete, EditPen } from '@element-plus/icons-vue'
import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import AssetLampPostOptions from './option'
import styles from '~/pages/assetManagement/index.module.scss'
import ExportExcel from '~/components/ExportExcel'
import ImportExcel from './ImportExcel'
import { isURL } from '~/utils/validate'

export default defineComponent(function BasestationCabinet() {
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<ValuesType>({})
  const state = reactive<AssetLampPostStateType>({
    importVisible: false, // 导入 弹窗是否显示
    exportVisible: false, // 导出 弹窗是否显示
    modalVisible: false, // 新增/编辑 弹窗是否显示
    type: 'read',
    record: {}
  })
  // 按钮权限
  const userState = useVuexGetters('user', ['permission'])
  const baseState = useVuexGetters('base', ['usageStatusOpt'])
  const store = useStore()
  const columns: TableColumnProps<ValuesType>[] = [
    {
      label: '机柜名称',
      prop: 'name',
      showOverflowTooltip: true,
      minWidth: 200,
      fixed: 'left',
      unFixed: true,
      sortable: true, //  排序
      disabled: true //  不可编辑
    },
    {
      label: '规格型号',
      prop: 'spec',
      showOverflowTooltip: true,
      minWidth: 220,
      sortable: true
    },
    {
      label: '使用状态',
      prop: 'useStatus',
      minWidth: 140,
      sortable: true,
      render: ({ row }) => (
        <>
          {row.useStatus === 0 && <div style="color: #0079FE;">建设中</div>}
          {row.useStatus === 1 && <div style="color: #008080;">已建成</div>}
          {row.useStatus === 2 && <div style="color: #70B603;">已投运</div>}
        </>
      )
    },
    {
      label: '关联基站',
      prop: 'stationName',
      minWidth: 220,
      sortable: true
    },
    {
      label: '所属地区',
      prop: 'regionName',
      minWidth: 220,
      sortable: true
    },
    {
      label: '查看全景',
      prop: 'overallView',
      width: 88,
      sortable: false,
      render: ({ row }) => (
        <>
          {isURL(row.overallView) ? (
            <a href={row.overallView} target="_blank" style="cursor: pointer; color: blue;">
              查看全景
            </a>
          ) : (
            '-'
          )}
        </>
      )
    },
    {
      label: '备注',
      prop: 'memo',
      minWidth: 160,
      sortable: true,
      showOverflowTooltip: true
    },

    {
      label: '施工单位',
      prop: 'constrUnit',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '施工联系人',
      prop: 'constrPerson',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '经度',
      prop: 'lon',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '纬度',
      prop: 'lat',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '创建人',
      prop: 'createUser',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '修改人',
      prop: 'updateUser',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 160,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      disabled: true, //  不可编辑
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('basestation_cabinet_update') && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
              <ElIcon>
                <EditPen />
              </ElIcon>
              &nbsp; 编辑
            </ElLink>
          )}
          {userState.permission.value.has('basestation_cabinet_remove') && (
            <ElLink type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
              <ElIcon>
                <Delete />
              </ElIcon>
              &nbsp;删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]

  onMounted(async () => {
    //  使用状态
    store.dispatch('base/CabinetUseStatus', { code: 'asset_cabinet_use_status' })
  })

  // 新增/编辑
  const handleChangeOptionsModal = (type: AssetLampPostStateType['type'], record?: ValuesType) => {
    state.modalVisible = !state.modalVisible
    state.record = record || {}
    state.type = type
    if (!state.modalVisible && type !== 'read') proSaasTableRef.value!?.toSearch()
  }

  // 执行删除操作
  const handleDeleteSelectedData = async (params: string) => {
    await store
      .dispatch('base/GetCabinetRemove', {
        ids: params
      })
      .then((res) => {
        if (res?.code === 200) {
          proSaasTableRef.value!?.clearSelection?.()
          proSaasTableRef.value!?.toSearch()
          ElMessage({ type: 'success', message: '操作成功' })
        }
      })
  }

  // 打开删除消息确认框
  const handleOpenDeleteConfirm = (record?: ValuesType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要删除的数据' })
      return
    }
    const params =
      record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {record?.id && <p class="delete-title">确认删除数据?</p>}
          {!record?.id && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认删除选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认删除选中数据？'}
            </p>
          )}
          <p class="delete-content">删除后不可恢复，是否确认删除。</p>
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(() => {
        handleDeleteSelectedData(params)
      })
      .catch(() => {})
  }
  //   机柜名称
  const rowsName = ref(1)
  const onNameFocus = () => {
    rowsName.value = 4
  }
  const onNameBlur = () => {
    rowsName.value = 1
  }

  // 导入
  const handleChangeImportModal = () => {
    state.importVisible = !state.importVisible
    proSaasTableRef.value?.toSearch() // 刷新
  }

  // 导出
  const handleChangeExportModal = () => {
    state.exportVisible = !state.exportVisible
  }

  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }

  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  return () => {
    if (state.modalVisible) {
      return (
        <AssetLampPostOptions
          record={state.record}
          type={state.type}
          cancel={() => handleChangeOptionsModal('add')}
        />
      )
    }

    return (
      <ElCard>
        <ProSaasTable<ValuesType>
          tableId="cabinet"
          ref={proSaasTableRef}
          rowKey="id"
          hasSelection
          columns={columns}
          searchParams={{
            useStatus: formValues.useStatus?.join(',')
          }}
          searchFormProps={{
            model: formValues
          }}
          dispatchType="base/GetCabinetList"
          headerTitle={
            <>
              {userState.permission.value.has('basestation_cabinet_add') && (
                <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                  &nbsp; 新增
                </ElButton>
              )}
              {userState.permission.value.has('basestation_cabinet_import') && (
                <ElButton type="primary" onClick={() => handleChangeImportModal()}>
                  <AliIcon type="icon-daoru" />
                  &nbsp; 导入
                </ElButton>
              )}
              {userState.permission.value.has('basestation_cabinet_export') && (
                <ElButton type="primary" onClick={() => handleChangeExportModal()}>
                  <AliIcon type="icon-daochu" />
                  &nbsp; 导出
                </ElButton>
              )}
              {userState.permission.value.has('basestation_cabinet_remove') && (
                <ElButton type="danger" onClick={() => handleOpenDeleteConfirm()}>
                  <ElIcon>
                    <Delete />
                  </ElIcon>
                  &nbsp; 删除
                </ElButton>
              )}
            </>
          }
          searchformResponsiveCol={[
            <ElFormItem key="name" prop="name" label="">
              <ElInput
                v-model={formValues.name}
                {...{ rows: rowsName.value }}
                placeholder="机柜名称 多个回车换行"
                onKeydown={handleKeyDownEnterSubmitForm}
                onFocus={onNameFocus}
                onBlur={onNameBlur}
                type="textarea"
                style="position: absolute; top: 0; z-index: 99;"
              />
            </ElFormItem>,
            <ElFormItem key="useStatus" prop="useStatus" label="">
              <ElSelect
                v-model={formValues.useStatus}
                clearable
                multiple
                onChange={clearSearchTable}
                placeholder="使用状态"
              >
                {baseState.usageStatusOpt?.value?.map((item: shareEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="stationName" prop="stationName" label="">
              <ElInput
                v-model={formValues.stationName}
                {...{ maxlength: 30 }}
                placeholder="关联基站"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="constrUnit" prop="constrUnit" label="">
              <ElInput
                v-model={formValues.constrUnit}
                {...{ maxlength: 30 }}
                placeholder="施工单位"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>
          ]}
        ></ProSaasTable>
        {/* 导出 */}
        {state.exportVisible && (
          <ExportExcel
            visible={state.exportVisible}
            dispatchType="base/ExportCabinet"
            columns={proSaasTableRef.value?.filterColumns}
            payload={{ params: formValues }}
            exportNumber={proSaasTableRef.value?.pagination.total}
            onCancel={handleChangeExportModal}
          />
        )}

        {/* 导入 */}
        {state.importVisible && <ImportExcel doCancel={handleChangeImportModal} />}
      </ElCard>
    )
  }
})
